import {designComponent, reactive, useClassCache, useRefs} from "@peryl/react-compose";
import './RouterLogin.scss';
import {ApplicationConfigurationProvider, Button, Checkbox, Form, FormItem, i18n, Input, iValidateRule, lighter, ThemeColorSelector, ThemeDarkSelector, ThemeLocaleSelector, ThemeShapeSelector, ThemeSizeSelector} from "plain-design";
import {RouterLoginLocale} from "./RouterLogin.locale";
import {microApp} from "../microApp";
import {grassSvg} from "./grass.svg";
import {LoginService} from "../common/LoginService";
import Color from "color";
import {buildAssetsPath} from "../common/buildAssetsPath";
import {delay} from '@peryl/utils/delay';

i18n.setLangs(RouterLoginLocale);

export const RouterLogin = designComponent({
  setup() {

    const { refs, onRef } = useRefs({ form: Form });

    const state = reactive({
      loginInfo: {
        username: 'admin' as string | null,
        password: 'micro.pro' as string | null,
      },
    });

    const isMounted = (() => {
      const ret = reactive({ value: false });
      delay(23).then(() => ret.value = true);
      return ret;
    })();

    const classes = useClassCache(() => [
      'router-login',
      {
        'router-login-not-mounted': !isMounted.value
      },
    ]);

    const usernameValidator: iValidateRule["validator"] = ({ value }) => {
      if (value != null) {
        value = value.trim();
      }
      if (!value || !value.length) {
        return i18n.$intl('page.login.validate.username').d('用户名输入不正确！');
      }
    };

    const passwordValidator: iValidateRule['validator'] = ({ value }) => {
      if (value != null) {
        value = value.trim();
      }
      if (!value || !value.length) {
        return i18n.$intl('page.login.validate.password').d('密码输入不正确！');
      }
    };

    const login = async () => {
      refs.form?.clearValidate();
      await refs.form?.validate();
      const tokenInfo = await LoginService.loginPassword(state.loginInfo.username!, state.loginInfo.password!);
      const route = microApp.route.state.route!;
      if (!!route.query?.redirect) {
        microApp.route.history.replace(route.query?.redirect, { token: tokenInfo.token });
      } else {
        microApp.route.history.push('/crm');
      }
    };

    const configuration = ApplicationConfigurationProvider.inject();

    const baseColor = configuration.value.theme.vars['primary-6'].toLowerCase() == '#ffffff' ? '#888888' : lighter(configuration.value.theme.vars['primary-6'], 2, "hex");
    const baseRelativeColor = { h: 128, s: 59, l: 84 };

    const offsetColor = (colorString: string, h: number, s: number, l: number) => {
      const color = Color(colorString);
      const [_h, _s, _l] = color.hsl().array();
      return new Color({ h: _h + h - baseRelativeColor.h, s: _s + s - baseRelativeColor.s, l: (_l + l - baseRelativeColor.l) / (configuration.value.theme.dark ? 4 : 1) }).hex();
    };

    const color1 = offsetColor(baseColor, baseRelativeColor.h, baseRelativeColor.s, baseRelativeColor.l - 10);
    const color1Shadow = offsetColor(baseColor, 162, 29, 24);

    const color2 = offsetColor(baseColor, 132, 27, 54);
    const color2Shadow = offsetColor(baseColor, 170, 56, 20);

    const color3 = offsetColor(baseColor, 136, 48, 34);
    const color3Shadow = offsetColor(baseColor, 176, 69, 12);

    const color4 = offsetColor(baseColor, 140, 53, 26);
    const color4Shadow = offsetColor(baseColor, 182, 73, 4);

    const color5 = offsetColor(baseColor, 144, 60, 17);
    const color5Shadow = offsetColor(baseColor, 190, 86, 0);

    const color6 = offsetColor(baseColor, 148, 67, 3);

    // 128, 59, 84  -->> 162, 29, 43
    // 129, 27, 69  -->> 165, 56, 25
    // 158, 48, 35  -->> 186, 69, 17
    // 180, 53, 26  -->> 187, 73, 12
    // 181, 60, 17  -->> 180, 86, 3
    // 177, 67, 6

    // 179, 61, 18  -->> 189, 88, 3

    const bg2Styles = { backgroundImage: `linear-gradient(${color4}, ${color5} 100%)`, color: color6 };

    return () => (
      <div className={classes.value}>
        <svg className="router-login-background" viewBox="0 0 1440 800" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect width="1440" height="800" fill={color6}/>
          <g>
            <g>
              <path d="M724 605.5C562.4 438.3 552.833 202.167 567 117.5L1400 0L1384 863.5C1214.17 870.667 873.099 876.5 867.499 842.5C860.499 800 926 814.5 724 605.5Z" fill={color5} filter={`drop-shadow(2px 4px 60px ${color5Shadow})`}/>
            </g>
            <g>
              <path d="M888.001 585C618.001 505 551.501 162.667 552.001 1.5H931L1401.5 0C1434.17 856.667 1451.89 985.334 1309 800C1176 627.5 1225.5 685 888.001 585Z" fill={color4} filter={`drop-shadow(2px 4px 60px ${color4Shadow})`}/>
            </g>
            <g>
              <path d="M944.5 460C776.66 322.741 740 93.6667 739.5 0H928L1440 0V800.5H1317C1326.5 736 1307 628.314 1236.5 594.5C1126 541.5 1062.5 556.5 944.5 460Z" fill={color3} filter={`drop-shadow(2px 4px 120px ${color3Shadow})`}/>
            </g>
            <g>
              <path d="M1149.5 475C847.5 413.8 766.333 132.833 763.5 0H1105.5L1400 0C1353 480.5 1319.5 477.53 1295 480.5C1262 484.5 1220 489.287 1149.5 475Z" fill={color2} filter={`drop-shadow(2px 4px 100px ${color2Shadow})`}/>
            </g>
            <g>
              <path d="M1234 358.5C1088.8 246.1 1085.5 72 1102 0H1440V649C1432.83 599 1379.2 470.9 1234 358.5Z" fill={color1} filter={`drop-shadow(2px 4px 160px ${color1Shadow})`}/>
            </g>
            {/*<g>
              <path d="M505.5 622C481.281 597 444 511 438.5 510C433 509 416.101 508.7 396.501 545.5C372.001 591.5 432.5 651.5 458 669.5C483.5 687.5 541.5 706.249 541.5 674C541.5 647.5 536.5 654 505.5 622Z" fill={color5} filter={`drop-shadow(2px 4px 60px ${color5Shadow})`}/>
            </g>*/}
          </g>
        </svg>
        <div className="router-login-background2" style={bg2Styles}/>
        <div className="router-login-header-selector">
          <ThemeColorSelector/>
          <ThemeDarkSelector/>
          <ThemeShapeSelector/>
          <ThemeSizeSelector/>
          <ThemeLocaleSelector/>
        </div>
        <div className="router-login-content">
          {grassSvg()}
          <div className="router-login-title">
            <img src={buildAssetsPath('images/pro_logo.png')} alt=""/>
            <span>{i18n.$intl('page.login.title').d('Micro Pro')}</span>
            <ThemeLocaleSelector/>
          </div>
          <div className="router-login-form">
            <div className="router-login-desc">
              {i18n.$intl('page.login.description').d('基于微前端架构，开箱即用的中后台前端解决方案，支持多主题、多尺寸、多语言等丰富配置')}
            </div>
            <Form size="normal" colon={false} modelValue={state.loginInfo} ref={onRef.form} validateMessagePosition="bottom-right">
              <FormItem
                field="username"
                label={null}
                validator={usernameValidator}
              >
                <Input
                  v-model={state.loginInfo.username}
                  placeholder={`${i18n.$intl('page.login.username').d('用户名')}: admin or user`}
                  inputMode="stroke"
                  prefixIcon="pi-user"
                  size="large"
                />
              </FormItem>
              <FormItem
                field="password"
                label={null}
                validator={passwordValidator}
              >
                <Input
                  v-model={state.loginInfo.password}
                  placeholder={`${i18n.$intl('page.login.password').d('密码')}: micro.pro`}
                  type="password"
                  inputMode="stroke"
                  prefixIcon="pi-lock"
                  size="large"
                  nativeAttrs={{ autoComplete: 'off' }}
                />
              </FormItem>
            </Form>
            <div className="router-login-setting">
              <Checkbox label={i18n.$intl('page.login.keepLogin').d("自动登录")} modelValue={true}/>
              <Button mode="text" label={i18n.$intl('page.login.forgotPassword').d("忘记密码？")}/>
            </div>
            <Button className="router-login-submit-button" size="large" label={i18n.$intl('page.login.login').d("登录")} block mode="fill" asyncHandler={login}/>

            <div className="router-login-separator">
              <span>{i18n.$intl('page.login.otherLogin').d('其他登录方式')}</span>
            </div>
            <div className="router-login-other">
              <Button mode="text" icon="pi-wechat" status="secondary"/>
              <Button mode="text" icon="pi-alipay-circle" status="secondary"/>
              <Button mode="text" icon="pi-weibo" status="secondary"/>
            </div>
          </div>
        </div>
      </div>
    );
  },
});
